package org.mx.i8n;

import org.mx.StringUtils;
import org.mx.TypeUtils;
import org.mx.spring.i18n.I18nMessageResourceCreator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.AbstractMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 描述： 根据配置创建DSDB特有的自定义资源表创建器
 *
 * @author john peng Date time 2019/8/15 9:52 AM
 */
public class DsdbI18nMessageResourceCreator implements I18nMessageResourceCreator {
	private static final Logger logger = LoggerFactory.getLogger(DsdbI18nMessageResourceCreator.class);
	private Environment env;
	private JdbcTemplate jdbcTemplate;

	/**
	 * 构造函数
	 * 
	 * @param env          Spring环境
	 * @param jdbcTemplate JdbcTemplate
	 */
	public DsdbI18nMessageResourceCreator(Environment env, JdbcTemplate jdbcTemplate) {
		super();
		this.env = env;
		this.jdbcTemplate = jdbcTemplate;
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see I18nMessageResourceCreator#create()
	 */
	@Override
	public AbstractMessageSource create() {
		String tableName = env.getProperty("i18n.dsdb.table");
		String tablePrimary = env.getProperty("i18n.dsdb.tablePrimary");
		String langFieldsStr = env.getProperty("i18n.dsdb.langFields");
		if (StringUtils.isBlank(tableName) || StringUtils.isBlank(langFieldsStr)) {
			if (logger.isErrorEnabled()) {
				logger.error("The table's name or language fields is blank for the DSDB message resource.");
			}
			return null;
		}
		if (StringUtils.isBlank(tablePrimary)) {
			tablePrimary = "BM, ZDMC, ZDID";
		}
		String[] langFieldNames = StringUtils.split(langFieldsStr, ",", true, true);
		Map<String, String> langFields = new HashMap<>(langFieldNames.length);
		for (String langFieldName : langFieldNames) {
			String lang = env.getProperty(String.format("i18n.dsdb.langFields.%s", langFieldName));
			if (StringUtils.isBlank(lang)) {
				lang = langFieldName;
			}
			langFields.put(lang, langFieldName);
		}
		String strReloadTimeout = env.getProperty("i18n.reloadTimeout", "180 SEC");
		long reloadTimeout = TypeUtils.string2TimePeriod(strReloadTimeout, 180 * 1000);
		ReloadableDsDbResourceBundleMessageSource messageSource = new ReloadableDsDbResourceBundleMessageSource();
		messageSource.setCacheMillis(reloadTimeout);
		messageSource.setTableName(tableName);
		messageSource.setTablePrimary(tablePrimary);
		messageSource.setLangFields(langFields);
		messageSource.setJdbcTemplate(jdbcTemplate);
		return messageSource;
	}
}
